<?php
namespace Controller\Outlanderp4la\Cron;

use Hoa\Registry\Registry;
use Library\Log;
use Model\Outlanderp4la\SkuModel;
use Model\Outlanderp4la\DynCnfModel;


/**
 * SkuController
 * @author los_gsy
 */
class SkuController {
	/**
	 * 构造函数
	 */
	public function __construct() {
		parent::__construct();
	}


	/**
	 * test
	 */
	public function test() {
		echo __METHOD__;
	}


	/**
	 * 更新sku表
	 * 通过rpc方式调用sku基础资料库接口，来更新本地sku信息
	 */
	public function updateSkuList() {
		//环境
		set_time_limit(3600);

		Log::info(__METHOD__ . ' begin at: ' . date('Y-m-d H:i:s'));

		//定义变量
		$conf = Registry::get('conf');
		$cronAuth = $conf['outlanderp4la']['cron']['auth'];
		$skusystem = $conf['outlanderp4la']['api']['skusystem'];
		$page = 1;
		$pagesize = $skusystem['pagesize'];

		//获取参数
		$username = I('get.username');
		$passwd = I('get.passwd');

		//验证参数，即访问该Action的权限
		if ($username != $cronAuth['username'] || $passwd != $cronAuth['passwd']) {
			exit('Auth error');
		}

		//查询skusystem中sku的最新更新时间
		$dynCnf = DynCnfModel::getSkusystemSkuUpdatedAt4Outlanderp4la();
		$skuUpdatedAt = $dynCnf['v'];

		//通过skusystem接口，获取最近更新的sku列表
		do {
			$skuList = SkuModel::getSkuListFromSkusystemByUpdatedAt($skuUpdatedAt, $page, $pagesize);
// 			var_dump($skuList);
// 			exit;

			if ($skuList) {
				foreach ($skuList as $sku) {
					$skuData = [];
					$skuData['goods_sn'] = $sku['sku'];
					$skuData['SKU'] = $sku['sku'];
					$skuData['goods_name'] = $sku['name'];
					$skuData['nature'] = $sku['logistic'];
					$skuData['status'] = 2;
					$skuData['cost'] = $sku['cost'];
					$skuData['weight'] = $sku['packWeight'];
					$skuData['update_at'] = date('Y-m-d H:i:s');
					SkuModel::addOrSaveSkuByCode($skuData, $sku['sku']);
				}

				//更新动态配置表中，用于skusystem api调用的sku更新时间
				if ($sku['modifytime']) {
					$dynCnf['v'] = $sku['modifytime'];
					$dynCnf['update_at'] = date('Y-m-d H:i:s');
					DynCnfModel::saveDynCnf($dynCnf, $dynCnf['id']);
				}
				Log::info(__METHOD__ . ' cycle ' . $page . ' at: ' . date('Y-m-d H:i:s'));
			}

			$page++;
		} while($skuList);

		//Success
		Log::info(__METHOD__ . ' end at: ' . date('Y-m-d H:i:s'));
		exit('Success');
	}


}